//
//  InitManager.m
//  CustomerServer
//
//  Created by 涂俊 on 2019/7/25.
//  Copyright © 2019 Facebook. All rights reserved.
//

#import "InitManager.h"
#import "ArgumentStore.h"
#import "ImManager.h"

#import "SuperSDKPluginTools/SSDKPluginJsonUtil.h"
#import "SuperSDKPluginTools/SSDKPluginHttpUtil.h"
#import "SuperSDKPluginTools/SSDKPluginEncryptUtil.h"

@implementation InitManager

//单例
static InitManager *instance = nil;

+ (instancetype)getInstance {
    if (instance == nil) {
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            instance = [[self alloc] init];
        });
    }
    return instance;
}

- (void)initWithAppId:(NSString *)appId uid:(NSString *)uid roleId:(NSString *)roleId
             callback:(InitResultBlock)callback {
    ArgumentStore *store = [ArgumentStore instanceForKey:appId];
    NSString *initUrl = [[store baseUrl] stringByAppendingString:@"/init"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    UInt64 time = [[NSDate date] timeIntervalSince1970] * 1000;
    [params setValue:[NSString stringWithFormat:@"%llu", time] forKey:@"time"];
    [params setValue:appId forKey:@"appId"];
    [params setValue:uid forKey:@"appUid"];
    [params setValue:roleId forKey:@"appRoleId"];
    NSString *sign = [SSDKPluginEncryptUtil generateSignWithDictionary:params useSignKey:[store pubKey]];
    [params setValue:sign forKey:@"sign"];
    [SSDKPluginHttpUtil postWithUrl:initUrl
                               data:params
                           delegate:^(BOOL networkAvaliable, NSInteger status, NSString *resData) {
        NSLog(@"客服初始化接口,url=%@,status=%ld,httpResponse=%@", initUrl, (long)status, resData);
        if (!networkAvaliable) {
            NSLog(@"客服初始化接口,网络不可用!url=%@", initUrl);
            if (callback) {
                callback(NO);
            }
            return;
        }
        NSMutableDictionary *resDic = nil;
        if (200 == status) {
            @try {
                resDic = [SSDKPluginJsonUtil toObjectWithJson:resData];
            }
            @catch (NSException *exception) {
                NSLog(@"客服初始化接口,返回处理异常,exception=%@,reason=%@", exception.name, exception.reason);
            }
        }
        if (resDic == nil || [resDic count] == 0) {
            NSLog(@"客服初始化接口,返回为空!url=%@", initUrl);
            if (callback) {
                callback(NO);
            }
            return;
        }
        NSString *retStatus = [resDic valueForKey:@"status"];
        if (![@"ok" isEqualToString: retStatus]) {
            if (callback) {
                callback(NO);
            }
            return;
        }
        // 缓存初始化返回的配置
        [store setConfigInit:resData];
        // 将im账号密码持久化到本地
        NSDictionary *imDic = [resDic objectForKey:@"im"];
        if (imDic) {
            NSString *username = [imDic objectForKey:@"v1"];
            NSString *password = [imDic objectForKey:@"v2"];
            [store saveUserWithUid:uid roleId:roleId imUsername:username imPassword:password];
        }
        if (callback) {
            callback(YES);
        }
    }];
}

- (BOOL)loginWithAppId:(NSString *)appId uid:(NSString *)uid roleId:(NSString *)roleId {
    ArgumentStore *store = [ArgumentStore instanceForKey:appId];
    if (ArgumentStore.current == store) {
        return YES;
    }
    
    [[ImManager getInstance] imLogout];
    ArgumentStore.current.imLoginResult = @"fail";
    // 设置当前登录的store
    store.imLoginResult = @"logging";
    ArgumentStore.current = store;
    
    NSArray *imAccount = [store getUserByUid:uid roleId:roleId];
    if (imAccount == nil) {
        return NO;
    }
    NSString *username = [imAccount objectAtIndex:0];
    NSString *password = [imAccount objectAtIndex:1];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        // 再登录环信
        BOOL result = [[ImManager getInstance] imLoginWithUsername:username password:password];
        if (result) {
            // 通知rn层登录成功
            [[NSNotificationCenter defaultCenter] postNotificationName:@"im_login_ok" object:nil];
        }
    });
    return YES;
}

@end
